package cluster

import (
	"context"
	"krm-backend/config"
	"krm-backend/controllers"
	"krm-backend/utils/logs"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type StatisticsData struct {
	Name  string `json:"name"`
	Value int    `json:"value"`
}

// []StatisticsItem
type StatisticsItem struct {
	Id         string           `json:"id"`
	Header     string           `json:"header"`
	Total      int              `json:"total"`
	SeriesName string           `json:"seriesName"`
	Data       []StatisticsData `json:"data"`
}

func genericStatistics(clusterId, resourceType, displayName string, si *StatisticsItem) {
	count := controllers.ClusterStatistics[clusterId][resourceType]
	statisticsData := StatisticsData{
		Name:  displayName,
		Value: count,
	}
	si.Total += count
	si.Data = append(si.Data, statisticsData)
}

func Statistics(r *gin.Context) {
	logs.Debug(nil, "获取所有集群的资源统计信息")
	//直接获取列表
	listOptions := metav1.ListOptions{
		LabelSelector: config.ClusterConfigSecretLabelKey + "=" + config.ClusterConfigSecretLabelValue,
	}
	returnData := config.ReturnData{}
	secretList, err := config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).List(context.TODO(), listOptions)
	if err != nil {
		logs.Info(map[string]interface{}{"msg": err.Error()}, "获取集群统计信息失败")
		//查询失败
		msg := "获取失败" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	var (
		activeTotal   int
		inActiveTotal int
	)
	nodeStatisticsItem := StatisticsItem{
		Id:         "node",
		Header:     "节点统计",
		Total:      0,
		SeriesName: "节点分布",
		Data:       []StatisticsData{},
	}
	nsStatisticsItem := StatisticsItem{
		Id:         "namespace",
		Header:     "命名空间统计",
		Total:      0,
		SeriesName: "命名空间分布",
		Data:       []StatisticsData{},
	}
	deploymentStatisticsItem := StatisticsItem{
		Id:         "deployment",
		Header:     "Deployment统计",
		Total:      0,
		SeriesName: "Deployment分布",
		Data:       []StatisticsData{},
	}
	podStatisticsItem := StatisticsItem{
		Id:         "pod",
		Header:     "Pod统计",
		Total:      0,
		SeriesName: "Pod分布",
		Data:       []StatisticsData{},
	}
	dsStatisticsItem := StatisticsItem{
		Id:         "DaemonSet",
		Header:     "DaemonSet统计",
		Total:      0,
		SeriesName: "DaemonSet分布",
		Data:       []StatisticsData{},
	}
	stsStatisticsItem := StatisticsItem{
		Id:         "StatefulSet",
		Header:     "StatefulSet统计",
		Total:      0,
		SeriesName: "StatefulSet分布",
		Data:       []StatisticsData{},
	}
	cronStatisticsItem := StatisticsItem{
		Id:         "CronJob",
		Header:     "CronJob统计",
		Total:      0,
		SeriesName: "CronJob分布",
		Data:       []StatisticsData{},
	}
	secretStatisticsItem := StatisticsItem{
		Id:         "Secret",
		Header:     "Secret统计",
		Total:      0,
		SeriesName: "Secret分布",
		Data:       []StatisticsData{},
	}
	cmStatisticsItem := StatisticsItem{
		Id:         "Configmap",
		Header:     "Configmap统计",
		Total:      0,
		SeriesName: "Configmap分布",
		Data:       []StatisticsData{},
	}
	svcStatisticsItem := StatisticsItem{
		Id:         "Service",
		Header:     "Service统计",
		Total:      0,
		SeriesName: "Service分布",
		Data:       []StatisticsData{},
	}
	ingressStatisticsItem := StatisticsItem{
		Id:         "Ingress",
		Header:     "Ingress统计",
		Total:      0,
		SeriesName: "Ingress分布",
		Data:       []StatisticsData{},
	}
	PVStatisticsItem := StatisticsItem{
		Id:         "PV",
		Header:     "PV统计",
		Total:      0,
		SeriesName: "PV分布",
		Data:       []StatisticsData{},
	}
	PVCStatisticsItem := StatisticsItem{
		Id:         "PVC",
		Header:     "PVC统计",
		Total:      0,
		SeriesName: "PVC分布",
		Data:       []StatisticsData{},
	}
	//查看每个集群的状态
	for _, clusterConfig := range secretList.Items {
		curClusterId := clusterConfig.Name
		curDisplayName := clusterConfig.Annotations["displayName"]
		logs.Debug(map[string]interface{}{"集群ID": curClusterId,
			"集群名称": curDisplayName}, "获取集群资源统计详情")
		//判断集群的状态
		if clusterConfig.Annotations["status"] == "Active" {
			activeTotal += 1
		} else {
			inActiveTotal += 1
		}
		//查询当前集群所有资源类型的总数
		//获取节点总数
		// nodeCount := controllers.ClusterStatistics[curClusterId]["Node"]
		// nodeStatisticsData := StatisticsData{
		// 	Name:  curDisplayName,
		// 	Value: nodeCount,
		// }
		// nodeStatisticsItem.Data = append(nodeStatisticsItem.Data, nodeStatisticsData)
		// //统计节点总数量
		// nodeStatisticsItem.Total += nodeCount
		genericStatistics(curClusterId, "Node", curDisplayName, &nodeStatisticsItem)
		genericStatistics(curClusterId, "Pod", curDisplayName, &podStatisticsItem)
		genericStatistics(curClusterId, "Namespace", curDisplayName, &nsStatisticsItem)
		genericStatistics(curClusterId, "Deployment", curDisplayName, &deploymentStatisticsItem)
		genericStatistics(curClusterId, "DaemonSet", curDisplayName, &dsStatisticsItem)
		genericStatistics(curClusterId, "StatefulSet", curDisplayName, &stsStatisticsItem)
		genericStatistics(curClusterId, "CronJob", curDisplayName, &cronStatisticsItem)
		genericStatistics(curClusterId, "Secret", curDisplayName, &secretStatisticsItem)
		genericStatistics(curClusterId, "Configmap", curDisplayName, &cmStatisticsItem)
		genericStatistics(curClusterId, "Service", curDisplayName, &svcStatisticsItem)
		genericStatistics(curClusterId, "Ingress", curDisplayName, &ingressStatisticsItem)
		genericStatistics(curClusterId, "PV", curDisplayName, &PVCStatisticsItem)
		genericStatistics(curClusterId, "PVC", curDisplayName, &PVStatisticsItem)

	}
	clusterActiveData := StatisticsData{
		Name:  "Active",
		Value: activeTotal,
	}
	clusterInActiveData := StatisticsData{
		Name:  "InActive",
		Value: inActiveTotal,
	}
	clusterStatisticsItem := StatisticsItem{
		Id:         "cluster",
		Header:     "集群统计",
		Total:      len(secretList.Items),
		SeriesName: "集群状态分布",
		Data:       []StatisticsData{},
	}
	clusterStatisticsItem.Data = append(clusterStatisticsItem.Data, clusterActiveData, clusterInActiveData)
	//汇总统计信息
	var statisticsItemList []StatisticsItem
	statisticsItemList = append(statisticsItemList,
		clusterStatisticsItem,
		nodeStatisticsItem,
		nsStatisticsItem,
		podStatisticsItem,
		deploymentStatisticsItem,
		dsStatisticsItem,
		stsStatisticsItem,
		cronStatisticsItem,
		secretStatisticsItem,
		cmStatisticsItem,
		svcStatisticsItem,
		ingressStatisticsItem,
		PVStatisticsItem,
		PVCStatisticsItem,
	)

	returnData.Status = 200
	returnData.Message = "查询成功"
	returnData.Data = make(map[string]interface{})
	returnData.Data["items"] = statisticsItemList
	r.JSON(200, returnData)

}
